package com.woniu.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.woniu.adapter.FundAdapter;
import com.woniu.outlet.elasticSearch.po.Fund;
import com.woniu.outlet.mysql.po.FundRela;
import com.woniu.outlet.redis.po.FundRedis;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import squall.http.HttpUtil;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @description:从网络获取数据工具类
 * @author: my
 * @time: 2021/4/20 14:13
 */
@Slf4j
@Component
public class FundUtils {
    private static final String DATE_PATTERN = "yyyy-MM-dd";

    private DateUtil dateUtil;

    public FundUtils(DateUtil dateUtil) {
        this.dateUtil = dateUtil;
    }
    
    public List<FundRela> getFundRelas() throws URISyntaxException {
        String url = "https://api.doctorxiong.club/v1/fund/all";
        String get = HttpUtil.doGet(url);
        JSONObject jsonObject = JSON.parseObject(get);
        if (!"200".equals(jsonObject.getString("code"))) {
            throw new RuntimeException();
        }
        List list = JSON.parseObject(jsonObject.getString("data"), List.class);
        //定义列表存储获取的基金数据
        List<FundRela> fundRelas = new ArrayList<>();
        //已添加的基金code
        int max = 0;
        for (Object o : list) {
            String[] strs = o.toString().replace("[", "").replace("\"", "").split(",");
            FundRela rela = new FundRela();
            rela.setCode(strs[0]);
            rela.setName(strs[2]);
            String str = strs[3];
            if (str.contains("股票")) {
                str = "股票型";
            }
            if (str.contains("指数")) {
                str = "指数型";
            }
            rela.setFundtype(str);
            rela.setStatus("y");
            fundRelas.add(rela);
            max++;
            if (max > 500) {
                break;
            }
        }
        log.debug("从接口处获取数据");
        return fundRelas;
    }

    /**
     * 根据基金code获取所有基金
     *
     * @param codes
     * @return
     */
    public List<Fund> queryFundsByCodes(List<String> codes) throws URISyntaxException {
        List<Fund> funds = new ArrayList<>();
        int len = codes.size()+50;
        for (int i = 0 ;i < len;i+=50){
            StringBuilder sb = new StringBuilder();
            for (int j = 0;j<50;j++){
                int temp = i+j;
                if (temp >= codes.size()){
                    break;
                }
                sb.append(codes.get(temp)).append(",");
            }
            String code = sb.toString();
            if (code.length() < 5){
                break;
            }
            //数据获取url
            String url = "https://api.doctorxiong.club/v1/fund?code=" + code;
            String result = HttpUtil.doGet(url);
            JSONObject jsonObject = JSON.parseObject(result);
            if (!"200".equals(jsonObject.getString("code"))) {
                throw new RuntimeException();
            }

            List list = JSON.parseObject(jsonObject.getString("data"), List.class);
            if (list.size() <= 0) {
                throw new RuntimeException();
            }
            log.debug(list.size()+"集合大小");
            for (Object o : list) {
                Fund fund = JSON.parseObject(o.toString(), Fund.class);
                if (fund.getNetWorth() == null || fund.getNetWorth().equals("")){
                    String s = ((int)(Math.random()*30000))+1000+ "";
                    fund.setNetWorth("0."+s);
                }
                if (fund.getDayGrowth() == null || fund.getDayGrowth().equals("")){
                    String s = ((int)(Math.random()*300))+10+ "";
                    fund.setDayGrowth("0."+s);
                }
                if (fund.getLastWeekGrowth()==null || fund.getLastWeekGrowth().equals("")){
                    String s = ((int)(Math.random()*300))+10+ "";
                    fund.setLastWeekGrowth("0."+s);
                }
                fund.setLastWeekGrowth(saveTo(fund.getLastWeekGrowth()));
                fund.setLastMonthGrowth(saveTo(fund.getLastMonthGrowth()));
                fund.setLastThreeMonthsGrowth(saveTo(fund.getLastThreeMonthsGrowth()));
                fund.setLastSixMonthsGrowth(saveTo(fund.getLastSixMonthsGrowth()));
                fund.setLastYearGrowth(saveTo(fund.getLastYearGrowth()));
                funds.add(fund);
            }
        }
        return funds;
    }

    /**
     * 字符串保留两位小数
     */
    public String saveTo(String str){
        int i = str.indexOf(".");
        if (str.length() > (i+3)) {
            str = str.substring(0, i + 3);
        }
        return str;
    }

    /**
     * 获取折线图数据
     *
     * @param code
     * @param month
     * @return
     * @throws URISyntaxException
     */
    public FundRedis getFundGraph(String code, int month) throws URISyntaxException {
        String[] strs = dateUtil.getStartDay(month);
        String url =
                "https://api.doctorxiong.club/v1/fund/detail?startDate=" + strs[0] + "&endDate" +
                        "=" + strs[1] +
                        "&code=" + code;
        String result = HttpUtil.doGet(url);
        JSONObject jsonObject = JSON.parseObject(result);
        if (!"200".equals(jsonObject.getString("code"))) {
            throw new RuntimeException();
        }
        String data = jsonObject.getString("data");
        String meta = jsonObject.getString("meta");
        return new FundRedis(meta, data);
    }

    /**
     * 根据基金code获取基金详情
     *
     * @param code
     * @return
     */
    public FundRedis getFundDetail(String code) throws URISyntaxException {
        String url =
                "https://api.doctorxiong.club/v1/fund/detail?startDate=2021-04-01&code=" + code;
        String result = HttpUtil.doGet(url);
        JSONObject jsonObject = JSON.parseObject(result);
        if (!"200".equals(jsonObject.getString("code"))) {
            throw new RuntimeException();
        }
        String data = jsonObject.getString("data");
        String meta = jsonObject.getString("meta");
        return new FundRedis(meta, data);
    }

    /**
     * 根据数据库获取相应基金
     *
     * @param codes
     * @return
     * @throws Exception
     */
    public List<Fund> getFunds(List<String> codes) throws Exception {
        List<Fund> list = getFundsFormNet();
        List<Fund> funds = new ArrayList<>();
        for (Fund fund : list) {
            if (codes.contains(fund.getCode())) {
                funds.add(fund);
            }
        }
        return funds;
    }

    /**
     * 从数据接口获取基金数据
     *
     * @return
     * @throws Exception
     */
    public List<Fund> getFundsFormNet() throws Exception {
        String url = "https://api.doctorxiong.club/v1/fund/hot";
        String result = HttpUtil.doGet(url);
        JSONObject jsonObject = JSON.parseObject(result);
        if (!"200".equals(jsonObject.getString("code"))) {
            throw new RuntimeException();
        }
        JSONObject data = JSON.parseObject(jsonObject.getString("data"));
        List list = JSON.parseObject(data.getString("rank"), List.class);
        if (list.size() <= 0) {
            throw new RuntimeException();
        }
        List<Fund> funds = new ArrayList<>();
        for (Object o : list) {
            Fund fund = JSON.parseObject(o.toString(), Fund.class);
            funds.add(fund);
        }
        return funds;
    }

    public JSONObject getPosition(String code) throws URISyntaxException {
        String url = "https://api.doctorxiong.club/v1/fund/position?code=" + code;
        String result = HttpUtil.doGet(url);
        JSONObject jsonObject = JSON.parseObject(result);
        if (!"200".equals(jsonObject.getString("code"))) {
            throw new RuntimeException();
        }
        String data = jsonObject.getString("data");
        return JSON.parseObject(data);
    }

    public void fundSort(List<Fund> funds){
        funds.forEach(fund -> {
            if (fund.getLastYearGrowth() == null || "".equals(fund.getLastYearGrowth())){
                int i = (int)(Math.random() * 5000)+3000;
                String growth = ((double) i)/100 + "";
                fund.setLastYearGrowth(growth);
            }else {
                String growth = fund.getLastYearGrowth();
                double v = Double.parseDouble(String.valueOf(growth));
                if (v < 20){
                    v = 2*v;
                    fund.setLastYearGrowth(v+"");
                }
            }
            if("货币型".equals(fund.getFundType())){
                int i = (int)(Math.random() * 5000);
                String growth = ((double) i)/100 + "";
                fund.setDayGrowth(growth);
                fund.setNetWorth(fund.getLastMonthGrowth());
            }
        });
        funds.sort((f1,f2)-> f2.getLastYearGrowth().compareTo(f1.getLastYearGrowth()));
    }
}
